package kingone.phone_store_spring_practice.service.impl;

import kingone.phone_store_spring_practice.entity.BuyerAddress;
import kingone.phone_store_spring_practice.form.AddressForm;
import kingone.phone_store_spring_practice.repository.BuyerAddressRepository;
import kingone.phone_store_spring_practice.service.AddressService;
import kingone.phone_store_spring_practice.vo.AddressVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    private BuyerAddressRepository buyerAddressRepository;

    @Override
    public List<AddressVO> findAll() {
        List<BuyerAddress> all = buyerAddressRepository.findAll();
        List<AddressVO> addressVOList = all.stream().map(e -> new AddressVO(
                e.getAddressId(),
                e.getAreaCode(),
                e.getBuyerName(),
                e.getBuyerPhone(),
                e.getBuyerAddress()
        )).collect(Collectors.toList());

        return addressVOList;
    }

    @Override
    public void saveOrUpdate(AddressForm addressForm) {
        /*1.此处先根据id是否有值，进行判定是添加还是修改操作*/
        BuyerAddress buyerAddress;
        if(addressForm.getId() == null){
            //进行添加操作:先创建一个对象，对各属性进行赋值以后，在进行保存操作。
            buyerAddress = new BuyerAddress();
        } else {
            // 进行修改操作: 先根据id找到该对象，在对属性一一赋值即可。
            buyerAddress = buyerAddressRepository.findById(addressForm.getId()).get();
        }

        buyerAddress.setBuyerName(addressForm.getName());
        buyerAddress.setBuyerPhone(addressForm.getTel());
        buyerAddress.setAreaCode(addressForm.getAreaCode());

        //对于详细地址，需要将传过来的省市区等信息内容拼接起来
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(addressForm.getProvince())
                .append(addressForm.getCity())
                .append(addressForm.getCounty())
                .append(addressForm.getAddressDetail());
        buyerAddress.setBuyerAddress(stringBuffer.toString());

        buyerAddressRepository.save(buyerAddress);
    }
}
